import 'dart:convert';
import 'dart:math';

import 'package:flutter/cupertino.dart';

import '../../../data/db/models/bt_post.dart';
import '../../../data/db/models/bt_static_comment.dart';
import '../../../data/db/models/bt_static_post.dart';
import '../../../data/db/providers/bt_post_provider.dart';
import '../../../data/models/bt_broadcaster.dart';
import '../../../data/store/bt_hive_logon_store.dart';
import '../../message/repository/bt_message_repository.dart';
import '../../message/utils/bt_constants.dart';
import '../../utils/bt_event_bus.dart';

class BtPostDetailsModel extends ChangeNotifier {
  bool _isLoading = false;

  bool get isLoading => _isLoading;

  String _error = '';

  String get error => _error;

  String _authorId = '';

  String get authorId => _authorId;

  String _title = '';

  String get title => _title;

  String _subTitle = '';

  String get subTitle => _subTitle;

  String _content = '';

  String get content => _content;

  String _commentContent = '';

  String get commentContent => _commentContent;

  final List<BtStaticPost> _staticPosts = [];

  List<BtStaticPost> get staticPosts => _staticPosts;

  List<String> _picUrls = [];

  List<String> get picUrls => _picUrls;

  List<String> _comments = [];

  List<int> _likes = [];

  List<int> _likeStatuses = [];

  List<int> _followStatuses = [];

  List<int> _senders = [];

  List<BtStaticComment> _staticComments = [];

  List<BtStaticComment> get staticComments => _staticComments;

  late final String _authorName;

  late final String _avatar;

  int _followed = 0;

  String _cover = '';

  final Random random = Random();

  final BtPostProvider postProvider = BtPostProvider();
  late final BtMessageRepository repository;

  List<BtBroadcaster> _broadcasters = [];

  String _userId = '';
  String _username = '';
  String _userAvatar = '';

  BtPostDetailsModel(
      String title, String authorId, String authorName, String avatar, List<BtBroadcaster> broadcasters) {
    repository = BtMessageRepository();
    _title = title;
    _authorId = authorId;
    _authorName = authorName;
    _avatar = avatar;
    _broadcasters = broadcasters;
    _staticPosts.add(const BtStaticPost(
      title: 'Americano',
      subTitle: 'Do you like Americano?',
      content:
          '''Americano often retains some of the natural sweetness of the coffee bean, especially for Americanos made from quality beans. This slight sweetness brings a richer flavour to the coffee. The body is usually lighter, not too thick or greasy. It has a softer flavour than other coffee drinks such as espresso or lattes.''',
      followed: 11,
      cover: '',
      picUrls: [
        'assets/images/posts/bt_am_pexels_ariel.jpg',
        'assets/images/posts/bt_am_pexels_john.jpg',
        'assets/images/posts/bt_am_pexels_skylar.jpg',
        'assets/images/posts/bt_am_tumblr.jpg',
      ],
      comments: [
        '🤩 This cup of Americano has a smooth taste and is intoxicating!',
        '😍 The aroma and taste of the Americano is perfect!',
        '😋 One sip of Americano coffee will leave you with endless aftertaste, it’s so delicious!',
        '👌 This Americano is perfect and every sip is satisfying!',
        '💯 The Americano coffee tastes so good that you can’t put it down!',
        '😁 This cup of Americano brings a feeling of happiness and makes people feel happy inside!',
        '✨ The taste of American coffee is pure and intoxicating!',
        '😌 A sip of Americano coffee soothes the body and mind, making people feel peaceful and relaxed.'
      ],
      likes: [12, 15, 10, 12, 17, 20, 16, 18],
      likeStatuses: [0, 0, 0, 0, 0, 0, 0, 0],
      followStatuses: [0, 0, 0, 0, 0, 0, 0, 0],
      senders: [0, 0, 0, 0, 0, 0, 0, 0],
    ));
    _staticPosts.add(const BtStaticPost(
      title: 'Cappuccino',
      subTitle: 'Do you like Cappuccino?',
      content:
          '''When sipping a cappuccino, you can feel the layers of flavor from the bitterness of the espresso to the sweetness of the steamed milk and the smooth texture of the milk foam. This rich layer of texture makes cappuccino a fun and engaging coffee experience''',
      followed: 12,
      cover: '',
      picUrls: [
        'assets/images/posts/bt_cap_pexels_aphiwat.jpg',
        'assets/images/posts/bt_cap_pexels_chevanon.jpg',
        'assets/images/posts/bt_cap_pexels_jason.jpg',
      ],
      comments: [
        '👍 This cup of Americano has a delicate taste and is simply the pinnacle of coffee!',
        '😎 The taste of Americano coffee is unique and eye-catching!',
        '❤️ A cup of American coffee makes people feel the charm and warmth of coffee!',
        '🥰 The taste and aroma of this cup of Americano makes you happy!',
        '😋 The Americano coffee has a long aftertaste that makes you intoxicated!',
        '✨ This cup of Americano brings a pleasant enjoyment and makes people feel good!',
        '😊 Americano coffee has a rich taste and is a real pleasure to drink!'
      ],
      likes: [12, 15, 10, 12, 17, 14, 16],
      likeStatuses: [0, 0, 0, 0, 0, 0, 0],
      followStatuses: [0, 0, 0, 0, 0, 0, 0],
      senders: [0, 0, 0, 0, 0, 0, 0],
    ));
    _staticPosts.add(const BtStaticPost(
      title: 'Caramel Macchiato',
      subTitle: 'Do you like Caramel Macchiato?',
      content:
          '''Caramel sauce is an important component of caramel macchiato, which adds a rich caramel aroma to the coff   ee drink. This sweet aroma blends perfectly with the bitter taste of coffee, giving you a pleasant feeling''',
      followed: 16,
      cover: '',
      picUrls: [
        'assets/images/posts/bt_car_tumblr_5a8e.jpg',
        'assets/images/posts/bt_car_tumblr_08d.jpg',
        'assets/images/posts/bt_car_tumblr_ce5d5.jpg',
      ],
      comments: [
        '🍮 The sweetness and milky flavor of Caramel Macchiato are perfectly blended!',
        '😋 The caramel macchiato has a silky texture that makes you intoxicated!',
        '✨ Use caramel to add a unique sweet flavor to the macchiato!',
        '😍 The appearance and taste of Caramel Macchiato are irresistible!',
        '💕 Macchiato with caramel flavor is an ultimate enjoyment!',
        '🌟 Caramel Macchiato is a coffee choice that purely satisfies your taste buds!',
        '💯 Caramel Macchiato is a luxurious coffee treat you won’t want to stop!'
      ],
      likes: [12, 15, 10, 12, 17, 13, 16],
      likeStatuses: [0, 0, 0, 0, 0, 0, 0],
      followStatuses: [0, 0, 0, 0, 0, 0, 0],
      senders: [0, 0, 0, 0, 0, 0, 0],
    ));
    _staticPosts.add(const BtStaticPost(
      title: 'Espresso',
      subTitle: 'Do you like Espresso?',
      content:
          '''Espresso has a thick, rich taste, almost like a liquid chocolate. It leaves a rich, full texture on your tongue, allowing you to feel the depth and richness of the coffee beans''',
      followed: 26,
      cover: '',
      picUrls: [
        'assets/images/posts/bt_esp_pexels_karolina.jpg',
        'assets/images/posts/bt_esp_pexels_photo.jpeg',
        'assets/images/posts/bt_esp_tumblr_581dd.jpg',
      ],
      comments: [
        '💪 Espresso is the first choice for coffee lovers who pursue pure coffee taste!',
        '😍 The rich taste of espresso is intoxicating!',
        '🌟 A cup of espresso to awaken your taste buds and spirit!',
        '✨ The unique flavor of espresso is captivating and unforgettable!',
        '💕 The aroma of pure espresso is irresistible!',
        '🌸 Espresso is a powerful and energizing coffee choice!',
        '😋 Mellow and rich espresso allows you to enjoy the charm of coffee!',
        '✨ The unique characteristics of espresso make it a true piece of coffee art!'
      ],
      likes: [12, 15, 10, 12, 17, 13, 14, 16],
      likeStatuses: [0, 0, 0, 0, 0, 0, 0, 0],
      followStatuses: [0, 0, 0, 0, 0, 0, 0, 0],
      senders: [0, 0, 0, 0, 0, 0, 0, 0],
    ));
    _staticPosts.add(const BtStaticPost(
      title: 'Latte',
      subTitle: 'Do you like Caramel Latte?',
      content:
          '''Latte is a mixture of espresso and steamed milk, which has a very fine, silky texture. A sip of latte will give you a soft touch on your tongue, as if you are enjoying a smooth cloud-like texture.''',
      followed: 62,
      cover: '',
      picUrls: [
        'assets/images/posts/bt_lat_pexels_photo_2.webp',
        'assets/images/posts/bt_lat_pexels_photo.webp',
        'assets/images/posts/bt_lat_pexels_photo8.jpeg',
        'assets/images/posts/bt_lat_tumblr_21.jpg',
      ],
      comments: [
        '🥛 Definitely the classic choice among latte!',
        '❤️ The silky texture of latte is irresistible!',
        '✨ For coffee lovers, latte is the best choice!',
        '💕 The taste of latte makes people fall into sweet coffee fantasy!',
        '🌟 Starting the day with a latte is a luxurious treat!',
        '✨ The latte tastes as smooth as silk and is irresistible.',
        '🌸 The latte looks exquisite and tastes amazing!',
        '❤️ Latte is a coffee option full of warmth and comfort.'
      ],
      likes: [12, 15, 10, 12, 17, 13, 14, 16],
      likeStatuses: [0, 0, 0, 0, 0, 0, 0, 0],
      followStatuses: [0, 0, 0, 0, 0, 0, 0, 0],
      senders: [0, 0, 0, 0, 0, 0, 0, 0],
    ));

    eventBus.on<BtEventFn>().listen((event) {
      if (event.refresh == block) {
        String blockedId = event.obj as String;
        List<int> removeIndexes = [];
        _staticComments.removeWhere((element) {
          bool canRemove = element.userId == blockedId;
          if (canRemove) {
            removeIndexes.add(_staticComments.indexOf(element));
          }
          return canRemove;
        });
        for (var index in removeIndexes) {
          _comments.removeAt(index);
          _likes.removeAt(index);
          _likeStatuses.removeAt(index);
          _followStatuses.removeAt(index);
          _senders.removeAt(index);
        }
      }
    });

    _loadUserInfo();
  }

  Future<void> _loadUserInfo() async {
    var data = await BtHiveLogonStore().getData();
    _userId = data?.userId ?? '';
    _username = data?.nickname ?? '';
    _userAvatar = data?.avatarUrl ?? '';
  }

  void setCommentContent(String commentContent) {
    _commentContent = commentContent;
    notifyListeners();
  }

  void toggleLike(BtStaticComment comment, bool liked) {
    int index = _staticComments.indexOf(comment);
    if (index == -1) {
      return;
    }
    comment.liked = liked;
    comment.likes = liked ? comment.likes + 1 : comment.likes - 1;
    List<int> localLikes = [];
    List<int> localLikeStatuses = [];
    for (int i = 0; i < _likes.length; i++) {
      if (i == index) {
        localLikes.add(comment.likes);
        localLikeStatuses.add(comment.liked ? 1 : 0);
      } else {
        localLikes.add(_likes[i]);
        localLikeStatuses.add(_likeStatuses[i]);
      }
    }

    postProvider.update(BtPost(
      authorId: _authorId,
      authorName: _authorName,
      avatar: _avatar,
      title: _title,
      subTitle: _subTitle,
      content: _content,
      followed: _followed,
      cover: _cover,
      picUrls: jsonEncode(_picUrls),
      comments: jsonEncode(_comments),
      likes: jsonEncode(localLikes),
      likeStatuses: jsonEncode(localLikeStatuses),
      followStatuses: jsonEncode(_followStatuses),
      senders: jsonEncode(_senders),
    ));

    notifyListeners();
  }

  BtStaticPost _findPostByTitle(String title) {
    for (var item in _staticPosts) {
      if (item.title == title) {
        return item;
      }
    }

    return _staticPosts[random.nextInt(_staticPosts.length)];
  }

  Future<void> loadPost() async {
    try {
      _isLoading = true;
      notifyListeners();

      BtPost? post = await postProvider.getPost(_authorId);
      if (post != null) {
        _title = post.title;
        _picUrls = jsonDecode(post.picUrls).cast<String>();
        _subTitle = post.subTitle;
        _content = post.content;
        _followed = post.followed;
        _cover = post.cover;
        _comments = jsonDecode(post.comments).cast<String>();
        _likes = jsonDecode(post.likes).cast<int>();
        _likeStatuses = jsonDecode(post.likeStatuses).cast<int>();
        _followStatuses = jsonDecode(post.followStatuses).cast<int>();
        _senders = jsonDecode(post.senders).cast<int>();

        int length = _senders.length;
        for (int i = 0; i < length; i++) {
          int sender = _senders[i];
          _staticComments.add(BtStaticComment(
            userId: sender == 1 ? _userId : _broadcasters[i].userId,
            avatar: sender == 1 ? _userAvatar : _broadcasters[i].avatar,
            nickname: sender == 1 ? _username : _broadcasters[i].nickname,
            content: _comments[i],
            likes: _likes[i],
            liked: _likeStatuses[i] == 1,
            followed: _followStatuses[i] == 1,
            isSender: _senders[i] == 1,
            isLast: i == length - 1,
          ));
        }
      } else {
        BtStaticPost staticPost = _findPostByTitle(_title);
        _title = staticPost.title;
        _picUrls = staticPost.picUrls;
        _subTitle = staticPost.subTitle;
        _content = staticPost.content;
        _followed = staticPost.followed;
        _cover = staticPost.cover;
        _comments = staticPost.comments;
        _likes = staticPost.likes;
        _likeStatuses = staticPost.likeStatuses;
        _followStatuses = staticPost.followStatuses;
        _senders = staticPost.senders;

        int length = staticPost.comments.length;
        for (int i = 0; i < length; i++) {
          _staticComments.add(BtStaticComment(
            userId: _broadcasters[i].userId,
            avatar: _broadcasters[i].avatar,
            nickname: _broadcasters[i].nickname,
            content: _comments[i],
            likes: _likes[i],
            liked: _likeStatuses[i] == 1,
            followed: _followStatuses[i] == 1,
            isSender: _senders[i] == 1,
            isLast: i == length - 1,
          ));
        }

        await postProvider.insert(BtPost(
          authorId: _authorId,
          authorName: _authorName,
          avatar: _avatar,
          title: _title,
          subTitle: _subTitle,
          content: _content,
          followed: _followed,
          cover: _cover,
          picUrls: jsonEncode(_picUrls),
          comments: jsonEncode(_comments),
          likes: jsonEncode(_likes),
          likeStatuses: jsonEncode(_likeStatuses),
          followStatuses: jsonEncode(_followStatuses),
          senders: jsonEncode(_senders),
        ));
      }

      _isLoading = false;
      notifyListeners();
    } catch (error) {
      _error = error.toString();
      _isLoading = false;
      notifyListeners();
    }
  }

  BtStaticComment? _findCommentByUserId(String userId) {
    for (var item in _staticComments) {
      if (item.userId == userId) {
        return item;
      }
    }

    return null;
  }

  Future<void> sendComment(Function(bool) onResult) async {
    List<int> mutableLikes = List.from(_likes);
    List<String> mutableComments = List.from(_comments);
    List<int> mutableLikeStatuses = List.from(_likeStatuses);
    List<int> mutableFollowStatuses = List.from(_followStatuses);
    List<int> mutableSenders = List.from(_senders);
    List<BtStaticComment> mutableStaticComments = List.from(_staticComments);

    int followed = 0;
    BtStaticComment? comment = _findCommentByUserId(_authorId);
    if (comment != null) {
      followed = comment.followed ? 1 : 0;
    }
    mutableLikes.insert(0, 0);
    mutableComments.insert(0, _commentContent);
    mutableLikeStatuses.insert(0, 0);
    mutableFollowStatuses.insert(0, followed);
    mutableSenders.insert(0, 1);
    mutableStaticComments.insert(
        0,
        BtStaticComment(
          userId: _userId,
          avatar: _userAvatar,
          nickname: _username,
          content: _commentContent,
          likes: 0,
          liked: false,
          isLast: false,
          followed: followed == 1,
          isSender: true,
        ));
    _likes = List.from(mutableLikes);
    _comments = List.from(mutableComments);
    _likeStatuses = List.from(mutableLikeStatuses);
    _followStatuses = List.from(mutableFollowStatuses);
    _senders = List.from(mutableSenders);
    _staticComments = List.from(mutableStaticComments);

    int id = await postProvider.update(BtPost(
      authorId: _authorId,
      authorName: _authorName,
      avatar: _avatar,
      title: _title,
      subTitle: _subTitle,
      content: _content,
      followed: _followed,
      cover: _cover,
      picUrls: jsonEncode(_picUrls),
      comments: jsonEncode(_comments),
      likes: jsonEncode(_likes),
      likeStatuses: jsonEncode(_likeStatuses),
      followStatuses: jsonEncode(_followStatuses),
      senders: jsonEncode(_senders),
    ));

    setCommentContent('');
    await Future.delayed(const Duration(seconds: 1));
    notifyListeners();
    onResult(id > 0);
  }

  void addFriend(String followUserId, Function(bool success, String msg) onResult) {
    repository.addFriend(followUserId, onResult);
  }

  void updateFollowed(BtStaticComment comment) {
    List<int> localFollowStatuses = [];
    for (int i = 0; i < _staticComments.length; i++) {
      if (comment.userId == _staticComments[i].userId) {
        localFollowStatuses.add(1);
        _staticComments[i].followed = true;
      } else {
        localFollowStatuses.add(_followStatuses[i]);
      }
    }

    postProvider.update(BtPost(
      authorId: _authorId,
      authorName: _authorName,
      avatar: _avatar,
      title: _title,
      subTitle: _subTitle,
      content: _content,
      followed: _followed,
      cover: _cover,
      picUrls: jsonEncode(_picUrls),
      comments: jsonEncode(_comments),
      likes: jsonEncode(_likes),
      likeStatuses: jsonEncode(_likeStatuses),
      followStatuses: jsonEncode(localFollowStatuses),
      senders: jsonEncode(_senders),
    ));

    notifyListeners();
  }
}
